package com.lxl.controller;

import com.lxl.service.IService;
import com.lxl.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * @author 北上寻海
 */
@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //乱码问题
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        IService userService = new UserServiceImpl();
        //七天免登录验证，看之前是否有存到cookie进去，拿出来连数据库验证
        Cookie[] cookies = request.getCookies();
        String username = null;
        String password = null;
        List list =null;
        //置空判断，不然空值的话会出现空指针异常
        if(null!=cookies) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if ("username".equals(name)) {
                    username = cookie.getValue();
                } else if ("password".equals(name)) {
                    password = cookie.getValue();
                }
            }
        }
        try {
            list = userService.verify(username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if(list!=null){
            response.sendRedirect(request.getContextPath()+"/commonStaffWork.jsp");
        }else {
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }
    }
}
